import React from 'react';
import { Table, Badge, Typography, Popconfirm, Input, InputNumber, Form, Space, message, Modal, Button, Col, Row } from 'antd';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
//import { useLocation,useNavigate } from 'react-router-dom';
import { useGetdmdbcprojectsQuery, usePostadddmdbcprojectsMutation, usePuteditdmdbcprojectsMutation, useDeletdmdbcprojectsMutation, usePostdbcdatamonitorexcuteMutation } from '../../store/request/datamonitorrequests/dmdbcprojectsrequest';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useDeletdbcquartzremoveMutation } from '../../store/request/datamonitorrequests/quartzrequest';
//主要用于在前端全局状态中记录“当前有哪些监控正在运行”。
import { useDispatch } from 'react-redux';
import { addwatchState, removewatchState } from '../../store/slice/watchstateslice';


const { confirm } = Modal;

const inputNumberStyle = {
  width: '100%',
};
const DmDBCProjects = () => {
  const loginstate = useSelector(state => state.loginpara);//loginpara={isLogined,role:{key,loginname,authoritykey,avatarpath}}
  const [paraisselected, setparaisselected] = useState(false);//用于判断是否有选中行以此来空值执行按钮的生效
  const [selectpara, setselectpara] = useState("");//存储选中的行的数据
  // const [loading, setloading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);//设置表格里的是否选中异常值
  const dispatch = useDispatch();
  const watchstate = useSelector(state => state.watchstatepara);//标识监控的状态，watchstatepara这个名称由index.js定义


  //选中时选取异常值
  const handleSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setparaisselected(true); // 执行按钮可以使用
    setselectpara(selectedRows[0]); // 把选中行的异常值存储到state中

  };
  const rowSelection = {
    type: "radio",
    selectedRowKeys,
    onChange: handleSelectChange,
  };

  const [messageApi, contextHolder] = message.useMessage();
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const getRandomuserParams = (params) => ({
    pagesize: params.pagination?.pageSize,
    page: params.pagination?.current,
    loginname: loginstate.role.loginname
    //...params,
  });
  const [editingKey, setEditingKey] = useState(''); // 初始化正在编辑的 key 的 state
  //用于是否打开添加modal的表单页面
  const [open, setOpen] = useState(false);

  // const [badgestatus, setbadgestatus] = useState([]);

  //tableParams发生变化就会执行发送请求和参数
  const result = useGetdmdbcprojectsQuery(getRandomuserParams(tableParams));
  //对应的控制器是User_PropsController的ExcuteDataMonitor方法
  const [excutetrigger] = usePostdbcdatamonitorexcuteMutation();
  const [edittrigger] = usePuteditdmdbcprojectsMutation();
  const [deltrigger] = useDeletdmdbcprojectsMutation();
  const [addtrigger] = usePostadddmdbcprojectsMutation();
  const [delquartztrigger] = useDeletdbcquartzremoveMutation();

  const [form] = Form.useForm(); // 从 Form.useForm() 中解构 form
  const isEditing = (record) => record.key === editingKey; // 定义 isEditing 函数以检查记录是否正在被编辑


  const showConfirm = (r) => {
    confirm({
      title: '确认开始监控GZ压缩文件',
      icon: <ExclamationCircleOutlined />,
      content: '万事具备，只欠确认',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        //把选中行（项目）的 key 添加到全局监控状态中，标记这个项目“正在监控”。与后端无关
        dispatch(addwatchState(r.key));
        //跳转到监控页面
        //navigate("../beginmonitor", { replace: true, state: r })//..是指跳转到当前url的上一个url
        window.open(`${window.location.origin}/datamonitor/dbcbeginmonitor?p=${r.watchpath}`, "_blank");
      },
      onCancel() {
        //什么都不做
      },
    });
  };

  // 点击执行监控按钮的触发后台的User_PropsController的ExcuteDataMonitor方法，并开启一个新对话框
  const datamonitorexcute = async () => {

    // setloading(true);
    //selectpara是指选中的行数据
    const r = await excutetrigger(selectpara).unwrap();//执行后台的User_PropsController的ExcuteDataMonitor方法。初始化一次“数据监控任务”的运行环境，并将用户和系统的监控配置保存到内存缓存中，供后台定时任务使用
    // console.log(r);
    if (r.code === 200) {

      //存储选择的行数据，新窗口可以获取
      const userprop = `${selectpara.ip};${selectpara.vehicle};${selectpara.remarks};${selectpara.echart1title};${selectpara.echart2title};${selectpara.echart3title};${selectpara.echart4title};${selectpara.echart5title};${selectpara.echart6title};${selectpara.echart1chan};${selectpara.echart2chan};${selectpara.echart3chan};${selectpara.echart4chan};${selectpara.echart5chan};${selectpara.echart6chan};${selectpara.logpath};${selectpara.csvpath}`;
      localStorage.setItem(selectpara.watchpath, userprop);
      messagesucess(r.data);
      showConfirm(selectpara);
    } else {
      messageerror(r.data);
      // setexcutesuccess(0);
    }
    // setloading(false);
  };
  //点击取消监控按钮
  const datamonitorremove = async () => {

    // setloading(true);

    const r = await delquartztrigger(selectpara.watchpath).unwrap();
    const r2 = await delquartztrigger(selectpara.logpath).unwrap();
    //console.log(r);
    if (r.code === 200&&r2.code===200) {
      //删除数组中指定的元素
      // const newbadge=badgestatus.filter(item => item !== selectpara.key);
      // setbadgestatus(newbadge);
      dispatch(removewatchState(selectpara.key));
      messagesucess(r.data);

    } else {
      messageerror(r.data);
      // setexcutesuccess(0);
    }
    // setloading(false);

  };

  // 定义 edit 函数以将 editingKey state 设置为记录的 key
  //表单更新异常值只能用setFieldsValue方法，不能用setstate方法，这样就能获取原始值
  const edit = (record) => {

    form.setFieldsValue({
      ip: record.ip,
      vehicle: record.vehicle,
      watchpath: record.watchpath,
      logpath: record.logpath,
      dbcpath: record.dbcpath,
      csvpath: record.csvpath,
      echart1chan: record.echart1chan,
      echart1title: record.echart1title,
      echart2chan: record.echart2chan,
      echart2title: record.echart2title,
      echart3chan: record.echart3chan,
      echart3title: record.echart3title,
      echart4chan: record.echart4chan,
      echart4title: record.echart4title,
      echart5chan: record.echart5chan,
      echart5title: record.echart5title,
      echart6chan: record.echart6chan,
      echart6title: record.echart6title,
      remarks: record.remarks,
      email: record.email,
      person: record.person,
      odo: record.odo,
      can0: record.can0,
      idcount: record.idcount,
      frontdis: record.frontdis,
      reardis: record.reardis,
      //...record,  //一展开record，就会报错date.locale is not a function，但是之前arriveddate已经赋值为空字符串，所以除了arriveddate为空外，其余属性按照record展开
    });

    setEditingKey(record.key);
  };

  const messageerror = (editordel) => {
    //message.success('This is a success message');
    messageApi.open({
      type: 'error',
      content: editordel,
    });
    //console.log("消息框");
  };
  const messagesucess = (editordel) => {
    messageApi.open({
      type: 'success',
      content: editordel,
    });
  };
  //添加异常值的表单页面
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal width={1000}
        open={open}
        title="添加监控车辆"
        maskClosable={false}
        okText="添加"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={6}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="vehicle"
                label="车号"
                placeholder="请填写车号"
                rules={[
                  {
                    required: true,
                    message: '请输入车号!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="ip"
                label="主机号"
                placeholder="请填写主机号"
                rules={[
                  {
                    required: true,
                    message: '请输入主机号!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="remarks"
                label="主题"
                initialValue="全球路谱智能预测系统"
                rules={[
                  {
                    required: true,
                    message: '请输入主题!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

            </Col>
          </Row>

          <Row gutter={[16, 24]}>
            <Col span={6}>
              <Form.Item
                name="watchpath"
                label="GZ压缩文件监控路径"
                rules={[
                  {
                    required: true,
                    message: '请输入GZ压缩文件监控路径!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="logpath"
                label="日志监控路径"
                rules={[
                  {
                    required: true,
                    message: '请输入日志监控路径!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="dbcpath"
                label="DBC文件路径"
                rules={[
                  {
                    required: true,
                    message: '请输入DBC文件路径!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="dbcpath"
                label="CSV保存路径"
                rules={[
                  {
                    required: true,
                    message: '请输入CSV保存路径!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>


          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="echart1title"
                label="图表1主题"
                initialValue="轮心加速度X"
                rules={[
                  {
                    required: true,
                    message: '请输入图表1主题!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="echart2title"
                label="图表2主题"
                initialValue="轮心加速度Y"
                rules={[
                  {
                    required: true,
                    message: '请输入图表2主题!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="echart3title"
                label="图表3主题"
                initialValue="轮心加速度Z"
                rules={[
                  {
                    required: true,
                    message: '请输入图表3主题!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[16, 24]}>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart4title"
                label="图表4主题"
                initialValue="塔柱加速度X"
                rules={[
                  {
                    required: true,
                    message: '请输入图表4主题!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart5title"
                label="图表5主题"
                initialValue="塔柱加速度Y"
                rules={[
                  {
                    required: true,
                    message: '请输入图表5主题!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart6title"
                label="图表6主题"
                initialValue="塔柱加速度Z"
                rules={[
                  {
                    required: true,
                    message: '请输入图表6主题!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart1chan"
                label="图表1通道"
                initialValue="accxwhllf,accxwhlrf,accxwhllr,accxwhlrr"
                rules={[
                  {
                    required: true,
                    message: '请输入图表1通道!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart2chan"
                label="图表2通道"
                initialValue="accywhllf,accywhlrf,accywhllr,accywhlrr"
                rules={[
                  {
                    required: true,
                    message: '请输入图表2通道!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart3chan"
                label="图表3通道"
                initialValue="acczwhllf,acczwhlrf,acczwhllr,acczwhlrr"
                rules={[
                  {
                    required: true,
                    message: '请输入图表3通道!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>

          </Row>
          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart4chan"
                label="图表4通道"
                initialValue="accxstlf,accxstrf,accxstlr,accxstrr"
                rules={[
                  {
                    required: true,
                    message: '请输入图表4通道!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart5chan"
                label="图表5通道"
                initialValue="accystlf,accystrf,accystlr,accystrr"
                rules={[
                  {
                    required: true,
                    message: '请输入图表5通道!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="echart6chan"
                label="图表6通道"
                initialValue="acczstlf,acczstrf,acczstlr,acczstrr"
                rules={[
                  {
                    required: true,
                    message: '请输入图表6通道!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>

          </Row>
          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={5}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="person"
                label="负责人"
                rules={[
                  {
                    required: true,
                    message: '请输入负责人!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={5}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="odo"
                label="ODO列名"
                rules={[
                  {
                    required: true,
                    message: '请输入ODO列名!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={4}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="can0"
                label="can0标准量"
                rules={[
                  {
                    required: true,
                    message: '请输入can0标准量!',
                  },
                ]}
              >
                <InputNumber style={inputNumberStyle} min={0} />
              </Form.Item>
            </Col>
            <Col span={4}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="idcount"
                label="id标准量"
                rules={[
                  {
                    required: true,
                    message: '请输入id标准量!',
                  },
                ]}
              >
                <InputNumber style={inputNumberStyle} min={0} />
              </Form.Item>
            </Col>
            <Col span={3}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="frontdis"
                label="前位移标准值"
                rules={[
                  {
                    required: true,
                    message: '请输入前位移标准值!',
                  },
                ]}
              >
                <InputNumber style={inputNumberStyle} min={0} />
              </Form.Item>
            </Col>
            <Col span={3}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="reardis"
                label="后位移标准值"
                rules={[
                  {
                    required: true,
                    message: '请输入后位移标准值!',
                  },
                ]}
              >
                <InputNumber style={inputNumberStyle} min={0} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  };

  //这个方法页面加载时就会不停的执行
  const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { // 定义 EditableCell 组件并传入 props

    return (
      <td {...restProps}>
        {editing ? ( // 如果正在编辑，渲染带有相应 props 的 inputNode
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: `请输入${title}!`,
              },
            ]}
          >
            {dataIndex === "can0" || dataIndex === "idcount" ? <InputNumber min={0} /> : <Input />}
          </Form.Item>
        ) : (
          children // 否则渲染 children（文本）
        )}
      </td>
    );
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      editable: false,

      width: '1%',
      //render: (name) => `${name.first} ${name.last}`,
    },
    {
      title: '监控状态',
      key: 'state',
      render: (val, record) => <Badge status={watchstate.indexOf(record.key) === -1 ? "error" : "success"} />,
    },
    {
      title: '题目',
      dataIndex: 'remarks',
      editable: true,

    },
    {
      title: '主机号',
      dataIndex: 'ip',
      editable: true,

    },
    {
      title: '车号',
      dataIndex: 'vehicle',
      editable: true,

    },
    {
      title: 'GZ压缩文件路径',
      dataIndex: 'watchpath',
      editable: true,


    },
    {
      title: '日志路径',
      dataIndex: 'logpath',
      editable: true,

    },
    {
      title: 'DBC文件路径',
      dataIndex: 'dbcpath',
      editable: true,

    },
    {
      title: 'CSV保存路径',
      dataIndex: 'csvpath',
      editable: true,

    },
    {
      title: '主题1',
      dataIndex: 'echart1title',
      editable: true,

    },
    {
      title: '通道1',
      dataIndex: 'echart1chan',
      editable: true,
      width: '8%',
    },
    {
      title: '主题2',
      dataIndex: 'echart2title',
      editable: true,

    },
    {
      title: '通道2',
      dataIndex: 'echart2chan',
      editable: true,
      width: '8%',
    },
    {
      title: '主题3',
      dataIndex: 'echart3title',
      editable: true,

    },
    {
      title: '通道3',
      dataIndex: 'echart3chan',
      editable: true,
      width: '8%',
    },
    {
      title: '主题4',
      dataIndex: 'echart4title',
      editable: true,

    },
    {
      title: '通道4',
      dataIndex: 'echart4chan',
      editable: true,
      width: '8%',
    },
    {
      title: '主题5',
      dataIndex: 'echart5title',
      editable: true,

    },
    {
      title: '通道5',
      dataIndex: 'echart5chan',
      editable: true,
      width: '8%',
    },
    {
      title: '主题6',
      dataIndex: 'echart6title',
      editable: true,

    },
    {
      title: '通道6',
      dataIndex: 'echart6chan',
      editable: true,
      width: '8%',
    },



    {
      title: '负责人',
      dataIndex: 'person',
      editable: true,

    },
    {
      title: 'ODO列名',
      dataIndex: 'odo',

      editable: true,

    },
    {
      title: 'can0标准数据量',
      dataIndex: 'can0',
      editable: true,

    },

    {
      title: 'id标准数量',
      dataIndex: 'idcount',
      editable: true,

    },
    {
      title: '前位移标准',
      dataIndex: 'frontdis',
      editable: true,

    },
    {
      title: '后位移标准',
      dataIndex: 'reardis',
      editable: true,

    },
    {
      //表格最后的操作按钮
      title: '操作',
      dataIndex: 'action',
      width: '3%',
      fixed: 'right',
      render: (_, record) => { // 使用 Popconfirm 组件渲染操作列
        const editable = isEditing(record);//判断这一行的key是否为editingKey，如果是则说明点击了edit，如果不是则说明没有点击

        return editable ? (

          <span>
            <Typography.Link onClick={() => save(record.key)} style={{ marginRight: 8 }}>
              保存
            </Typography.Link>
            <Popconfirm title="确定取消吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>

        ) : (
          //点击了edit就把这一行的key设为editingKey，重新渲染，然后editable变为true，显示保存和取消a标签，editingKey不等于空说明有行点了edit，则其他行都是disabled
          <Space size="middle">
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </Typography.Link>

            <Popconfirm title="确定删除吗?" onConfirm={() => deldata(record.key)} onCancel={cancel} okText="Yes" cancelText="No">
              <a >
                删除
              </a>
            </Popconfirm>
          </Space>
        );

      },
    },
  ];
  //添加表单的添加方法
  const onAddDate = async (values) => {
    //console.log('Received values of form: ', values);
    setOpen(false);
    //补充添加时的登录用户名，传给后端用
    values.loginname = loginstate.role.loginname;
    //隐藏邮箱填写，直接默认
    // values.email = "yuxiaohui@saicmotor.com";
    const r = await addtrigger(values).unwrap();
    if (r.code === 200) {
      //console.log("成功")
      messagesucess(r.data);
      
    } else {
      messageerror(r.data);
    }

  };
  const save = async (key) => {
    //这里的row就是表单的所有项的值作为一个row对象存储
    //这里会异步
    const row = await form.validateFields();

    row.key = key;
    row.loginname = loginstate.role.loginname;

    //发送put请求到服务器
    const r = await edittrigger(row).unwrap();
    //console.log(r);
    if (r.code === 200) {
      //console.log("成功")
      messagesucess(r.data);

    } else {
      messageerror(r.data);
    }
    setEditingKey('');
    setSelectedRowKeys([]); // 清除表格选择
    setparaisselected(false);//保存时让button不起作用
  };

  const cancel = () => { // 定义 cancel 函数以重置 editingKey state
    setEditingKey('');

  };
  const deldata = async (key) => { // 定义 cancel 函数以重置 editingKey state
    //console.log(key);
    const r = await deltrigger(key).unwrap();
    if (r.code === 200) {
      //console.log("成功")
      messagesucess(r.data);

    } else {
      messageerror(r.data);
    }
    setEditingKey('');

  };
  const handleTableChange = (pagination, filters, sorter) => {

    setTableParams({
      pagination,
      //filters,
      // ...sorter,
    });

    // pagination分页异常值如果和tableParams里的分页异常值不一样，就把异常值清零，重新发送请求
    // if (pagination.pageSize !== tableParams.pagination?.pageSize) {
    //   setData([]);
    // }
  };
  //这个比EditableCell先执行，这个是点了edit后展示的form表单的设置
  const mergedColumns = columns.map((col) => { // 通过映射 columns 数组定义 mergedColumns 数组
    if (!col.editable) { // 如果列不可编辑，返回列
      return col;
    }

    return {
      ...col, // 否则返回编辑行新对象，其 render 函数为 EditableCell 组件
      onCell: (record) => (

        {

          record,
          //inputType: col.dataIndex === 'category' ? 'radio' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),//判断这一行的key是否为editingKey，为true说明这一行点击了edit
          // 将单元格的原始值传递给 EditableCell 组件

        }),
    };
  });

  //一旦tableParams发生改变，就调用此方法，当然第一次加载页面的时候也会调用此方法，所以第一次总是会去发送请求
  //useEffect 钩子函数将在组件渲染后执行 
  useEffect(() => {
    //如果请求成功则调用setTableParams方法

    if (result.isSuccess) {
      //console.log(result.data.pagedata);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: result.data.data.total,

        },
      });
    }

  }, [result.isSuccess]);

  // useEffect(() => {
  //   console.log(badgestatus);

  // }, [badgestatus]);


  return (
    <>
      {/* 必须把contextHolder包裹整个组件才能显示message消息框 */}
      {contextHolder}
      <Button
        onClick={() => {
          setOpen(true);
        }}
        type="primary"
        //如果是admdbcin登陆的就不需要执行添加特定用户参数
        //disabled={loginstate.role.loginname === "admdbcin"}
        style={{
          marginBottom: 16,
        }}
      // disabled={loginstate.role==="admdbcin"?false:true}
      >
        添加
      </Button>
      <CollectionCreateForm
        open={open}
        onCreate={onAddDate}
        onCancel={() => {
          setOpen(false);
        }}
      />
      <Form form={form} component={false}>

        <Table
          components={{
            body: {
              cell: EditableCell, // 使用 EditableCell 组件作为表格单元格
            },
          }}
          bordered
          rowHeight={100}
          rowSelection={rowSelection}
          dataSource={result.isSuccess ? result.data.data.pagedata : []} // 将 dataSource prop 设置为异常值 state
          columns={mergedColumns} // 将 columns prop 设置为 mergedColumns 数组
          rowClassName="editable-row"
          pagination={tableParams.pagination}
          loading={result.isLoading}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />
        <Form.Item>
          <Button
            block type="primary"
            size="large"

            disabled={!paraisselected}
            onClick={datamonitorexcute}
          >执行监控</Button>
        </Form.Item>
        <Form.Item>
          <Button
            block type="primary"
            size="large"
            danger
            disabled={!paraisselected}
            onClick={datamonitorremove}
          >取消监控</Button>
        </Form.Item>
      </Form>


    </>
  )
}

export default DmDBCProjects